package cn.exrick.service.impl;


import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.google.gson.Gson;

import cn.exrick.common.exception.NeedLoginException;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.mapper.TbMemberMapper;
import cn.exrick.pojo.TbMember;
import cn.exrick.pojo.TbMemberExample;
import cn.exrick.pojo.front.Member;
import cn.exrick.service.LoginService;
import cn.exrick.utils.DtoUtil;
import io.rong.RongCloud;
import io.rong.models.response.TokenResult;
import io.rong.models.user.UserModel;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private TbMemberMapper tbMemberMapper;
    @Autowired
    private JedisClient jedisClient;
    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;
    @Value("${rongcloud.appKey}")
    private String appKey;
    @Value("${rongcloud.appSecret}")
    private String appSecret;

    @Override
    public Member userLogin(String phone, String password) {

        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(1);
        criteria.andPhoneEqualTo(phone);
        List<TbMember> list = tbMemberMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            throw new XmallException("账号未注册");
        }
        TbMember tbMember = list.get(0);
        //md5加密
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(tbMember.getPassword())) {
            throw new XmallException("用户名或密码错误");
        }

        Member member = DtoUtil.TbMemer2Member(tbMember);
        if (member.getRongCloud() == null || "".equals(member.getRongCloud())) {
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            UserModel userModel = new UserModel();
            userModel.setId(tbMember.getId().toString());
            userModel.setName(tbMember.getUsername());
            userModel.setPortrait(tbMember.getFile() == null ? "default" : tbMember.getFile());
            try {
                TokenResult userGetTokenResult = rongCloud.user.register(userModel);
                if (userGetTokenResult.getCode() == 200) {
                    tbMember.setRongCloud(userGetTokenResult.getToken());
                    tbMemberMapper.updateByPrimaryKey(tbMember);
                    member.setRongCloud(userGetTokenResult.getToken());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String token = UUID.randomUUID().toString();
        member.setToken(token);
        member.setState(1);
        // 用户信息写入redis：key："SESSION:token" value："user"
        jedisClient.set("SESSION:" + token, new Gson().toJson(member));
//        jedisClient.expire("SESSION:" + token, SESSION_EXPIRE);//设置过期

        return member;
    }

    @Override
    public Member getUserByToken(String token) {

        String json = jedisClient.get("SESSION:" + token);
        if (json == null) {
            Member member = new Member();
            member.setState(0);
            throw new NeedLoginException("用户登录已过期");
        }
        //重置过期时间
//        jedisClient.expire("SESSION:" + token, SESSION_EXPIRE);
        Member member = new Gson().fromJson(json, Member.class);
        return member;
    }

    @Override
    public int logout(String token) {

        jedisClient.del("SESSION:" + token);
        return 1;
    }

    public Member findMemberByPhone(String phone) {
        TbMember tbMember = findByPhone(phone);
        if (tbMember == null) {
            return null;
        }
        return DtoUtil.TbMemer2Member(tbMember);
    }

    public TbMember findByPhone(String phone) {
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(1);
        criteria.andPhoneEqualTo(phone);
        List<TbMember> list = tbMemberMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            return null;
        }
        return list.get(0);
    }
}
